# import jusmargui
from PySide2.QtWidgets import (
    QApplication,
    QWidget,
    QTableWidgetItem,
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QVBoxLayout,
    QTabWidget,
    QGroupBox,
    QLabel,
    QLineEdit,
    QHBoxLayout,
    QGridLayout,
    QComboBox,
    QPushButton,
    QListWidget,
    QDialog,
    QButtonGroup,
    QRadioButton,
    QCheckBox,
    QListWidgetItem,
    QMessageBox,
    QGraphicsColorizeEffect,
    QFileDialog,
    QStyledItemDelegate,
    QSizePolicy,
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage, QIcon
import sys
import csv
import os
import json
import subprocess
import re
from ..util.parameter_mapping import (
    mainConnectMap,
    rodConnectMap,
    mainConnectReverseMap,
    rodConnectReverseMap,
    typeBundleMap,
    typeBundleReverseMap,
)
from gui.controls import envs
from .. import config as Config
from ..utils import Utils
from ..dlg_model_params import DlgModelMutliParams
from ..params_table import ParamsTable
from ..custom_widget import SelectBox, LineEditInt, SelectSearchBox
from ..bundle_connection.add_connection import DlgAddConnection


singleHeight = 60


class CustomTabWidget(QTabWidget):
    add_tab_signal = Signal()

    def __init__(self, parent=None):
        super(CustomTabWidget, self).__init__(parent)
        self.initUI()

    def initUI(self):
        # 设置标签位置
        self.setTabPosition(QTabWidget.North)

        # 创建右侧按钮
        addBtn = QPushButton()
        self.set_button_image(addBtn, "icons/plugins/qmodeling/add.png")
        addBtn.clicked.connect(self.add_tab_signal.emit)
        # lab.setFixedSize(30, 20)

        # 将按钮添加到标签栏
        self.tabBar().setLayoutDirection(Qt.LeftToRight)

        self.setCornerWidget(addBtn, Qt.TopRightCorner)

    def set_button_image(self, button, image_path):
        """设置按钮的图片，并保持等比宽高，同时设置边距"""
        pixmap = QPixmap(image_path)
        if pixmap.isNull():
            print("Error: Unable to load image.")
            return

        # 等比缩放图片到指定大小（15x15像素）
        scaled_pixmap = pixmap.scaled(
            15, 15, Qt.KeepAspectRatio, Qt.SmoothTransformation
        )

        # 将 QPixmap 转换为 QIcon
        icon = QIcon(scaled_pixmap)

        # 设置按钮图标和大小
        button.setIcon(icon)  # 使用 QIcon 设置图标
        button.setIconSize(scaled_pixmap.size())  # 设置图标大小
        button.setStyleSheet(
            """
                             QPushButton { 
                                margin-right:3px;
                                min-width: 25px !important; 
                                max-width: 25px !important; 
                                min-height: 15px !important; 
                                max-height: 15px !important;
                                border-bottom-left-radius: 0px;
                                border-bottom-right-radius: 0px; 
                             }"""
        )


class DlgBundleConnection2(DlgModelMutliParams):
    materialLibraryLocking_update_signal = Signal(object)
    bundleConnection_save_signal = Signal(object)

    def __init__(self, parent=None, params={}):
        super().__init__(parent)
        self.setWindowTitle("捆绑连接")
        self.resize(750, 700)

        self.mainWidgetDict = {}
        self.rodWidgetDict = {}

        self.connectType = "Stage"

        self.connects = params.get("connects") or {}

        self.info = self.parseContects(self.connects)

        self.materialOptions = self.getMaterialOption()

        layout = QVBoxLayout()

        self.tabs = CustomTabWidget()
        self.tabs.add_tab_signal.connect(self.addTab)
        self.mainPage = QWidget()
        self.rodPage = QWidget()
        self.tabs.addTab(self.mainPage, "主捆绑")
        self.tabs.addTab(self.rodPage, "捆绑连杆")

        self.createMainPage()
        self.createRodPage()

        layout.addWidget(self.tabs)

        btnLayout = QHBoxLayout()
        cancelBtn = QPushButton("取消")
        okBtn = QPushButton("确定")

        btnLayout.setAlignment(Qt.AlignCenter)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(cancelBtn)
        layout.addLayout(btnLayout)

        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)

        self.setLayout(layout)

        self.setMainStageOptions(
            options=(self.info.get("options0") or {}),
            select=self.mainWidgetDict["mainSection1"],
        )
        self.setMainStageOptions(
            options=(self.info.get("options1") or {}),
            select=self.mainWidgetDict["mainSection2"],
        )
        self.setRodStageOptions(
            options=(self.info.get("options0") or {}),
            select=self.rodWidgetDict["rodSection1"],
        )
        self.setRodStageOptions(
            options=(self.info.get("options1") or {}),
            select=self.rodWidgetDict["rodSection2"],
        )

        mainData = {}
        if Config.isLocation:
            self.cacheFile = Config.cachePath + "bundleConnection.json"
            mainData = Utils.read_json(self.cacheFile)
        else:
            mainData = params.get("data") or {}
            main = mainData.get("main") or {}
        self.updateUI(main, self.mainWidgetDict, "main")
        self.lastMaterials = Utils.getTableLibrarysName(
            data=main.get("mainBoltTable"), column=2
        )

        rodData = {}
        if Config.isLocation:
            self.cacheFile = Config.cachePath + "bundledConnectingRods.json"
            rodData = Utils.read_json(self.cacheFile)
        else:
            rodData = params.get("data") or {}
            rod = rodData.get("rod") or {}
        self.updateUI(rod, self.rodWidgetDict, "rod")
        self.lastMaterials = Utils.getTableLibrarysName(
            data=rod.get("mainRodsTable"), column=2
        )

        envs.ipimas_changeMaterial = (
            lambda library, *args, **kwargs: self.libraryChange(
                library, *args, **kwargs
            )
        )

    def createMainPage(self):

        # layoutWrap = QHBoxLayout()
        layout = QVBoxLayout()
        # layoutWrap.addStretch(1)
        # layoutWrap.addLayout(layout)
        # layoutWrap.addStretch(1)

        gridLayout = QGridLayout()
        self.section1GroupBox = QGroupBox(
            self.connects.get("connectsTitles")[0].get("title")
        )
        section1Layout = QVBoxLayout()
        self.section1GroupBox.setLayout(section1Layout)
        self.mainWidgetDict["mainSection1"] = SelectBox(
            options=[
                {"title": "点", "value": "点"},
                {"title": "蒙皮桁条", "value": "蒙皮桁条"},
            ],
            onChanged=lambda *args, **kwargs: self.mainSection1Changed(
                self, *args, **kwargs
            ),
        )

        self.mainWidgetDict["mainSection1Value"] = SelectSearchBox(options=[])
        self.mainWidgetDict["mainSection1"].setMinimumWidth(100)
        self.mainWidgetDict["mainSection1Value"].setMinimumWidth(100)
        self.mainWidgetDict["mainSection1"].setMaximumWidth(150)
        self.mainWidgetDict["mainSection1Value"].setMaximumWidth(150)
        section1Layout.addWidget(self.mainWidgetDict["mainSection1"])
        section1Layout.addWidget(self.mainWidgetDict["mainSection1Value"])

        coordinates1GroupBox = QGroupBox("支座点坐标")
        coordinates1Layout = QVBoxLayout()
        self.mainWidgetDict["mainCoordinates1Table"] = ParamsTable(rows=0, columns=3)
        self.mainWidgetDict["mainCoordinates1Table"].setFixedHeight(singleHeight)
        self.mainWidgetDict["mainCoordinates1Table"].setHorizontalHeaderLabels(
            [
                "id",
                "轴向坐标",
                "径向坐标",
            ]
        )
        self.mainWidgetDict["mainCoordinates1Table"].rowSetInt([0])
        self.mainWidgetDict["mainCoordinates1Table"].rowSetFloat([1, 2])
        coordinates1Layout.addWidget(self.mainWidgetDict["mainCoordinates1Table"])
        coordinates1GroupBox.setLayout(coordinates1Layout)
        section1Layout.addWidget(coordinates1GroupBox)

        self.mainscope1GroupBox = QGroupBox("支座范围")
        self.mainscope1GroupBox.setVisible(False)
        scope1Layout = QVBoxLayout()
        self.mainWidgetDict["mainScope1Table"] = ParamsTable(rows=0, columns=3)
        self.mainWidgetDict["mainScope1Table"].setFixedHeight(singleHeight)
        self.mainWidgetDict["mainScope1Table"].setHorizontalHeaderLabels(
            [
                "轴向起",
                "径向止",
                "角度",
            ]
        )

        self.mainWidgetDict["mainScope1Table"].rowSetFloat([0, 1, 2])
        self.mainWidgetDict["mainScope1Table"].useFlag = False
        scope1Layout.addWidget(self.mainWidgetDict["mainScope1Table"])
        self.mainscope1GroupBox.setLayout(scope1Layout)
        section1Layout.addWidget(self.mainscope1GroupBox)
        # section1Layout.addStretch(1)

        self.section2GroupBox = QGroupBox(
            self.connects.get("connectsTitles")[1].get("title")
        )
        section2Layout = QVBoxLayout()
        self.section2GroupBox.setLayout(section2Layout)
        self.mainWidgetDict["mainSection2"] = SelectBox(
            options=[],
            onChanged=lambda *args, **kwargs: self.mainSection2Changed(
                self, *args, **kwargs
            ),
        )
        self.mainWidgetDict["mainSection2Value"] = SelectSearchBox(options=[])
        self.mainWidgetDict["mainSection2"].setMinimumWidth(100)
        self.mainWidgetDict["mainSection2Value"].setMinimumWidth(100)
        self.mainWidgetDict["mainSection2"].setMaximumWidth(150)
        self.mainWidgetDict["mainSection2Value"].setMaximumWidth(150)
        section2Layout.addWidget(self.mainWidgetDict["mainSection2"])
        section2Layout.addWidget(self.mainWidgetDict["mainSection2Value"])

        coordinates2GroupBox = QGroupBox("支座点坐标")
        coordinates2Layout = QVBoxLayout()
        self.mainWidgetDict["mainCoordinates2Table"] = ParamsTable(rows=0, columns=3)
        self.mainWidgetDict["mainCoordinates2Table"].setFixedHeight(singleHeight)
        self.mainWidgetDict["mainCoordinates2Table"].setHorizontalHeaderLabels(
            [
                "id",
                "轴向坐标",
                "径向坐标",
            ]
        )
        self.mainWidgetDict["mainCoordinates2Table"].rowSetInt([0])
        self.mainWidgetDict["mainCoordinates2Table"].rowSetFloat([1, 2])
        coordinates2Layout.addWidget(self.mainWidgetDict["mainCoordinates2Table"])
        coordinates2GroupBox.setLayout(coordinates2Layout)
        section2Layout.addWidget(coordinates2GroupBox)

        self.mainscope2GroupBox = QGroupBox("支座范围")
        self.mainscope2GroupBox.setVisible(False)
        scope2Layout = QVBoxLayout()
        self.mainWidgetDict["mainScope2Table"] = ParamsTable(rows=0, columns=3)
        self.mainWidgetDict["mainScope2Table"].setFixedHeight(singleHeight)
        self.mainWidgetDict["mainScope2Table"].setHorizontalHeaderLabels(
            [
                "轴向起",
                "径向止",
                "角度",
            ]
        )

        self.mainWidgetDict["mainScope2Table"].rowSetFloat([0, 1, 2])
        self.mainWidgetDict["mainScope2Table"].useFlag = False
        scope2Layout.addWidget(self.mainWidgetDict["mainScope2Table"])
        self.mainscope2GroupBox.setLayout(scope2Layout)
        section2Layout.addWidget(self.mainscope2GroupBox)

        icon = envs.qicons.qicon_add()
        addImg = QLabel()
        addImg.setAlignment(Qt.AlignCenter)
        pixmap = icon.pixmap(20, 20)
        addImg.setPixmap(pixmap)

        gridLayout.addWidget(self.section1GroupBox, 0, 0)
        gridLayout.addWidget(addImg, 0, 1)
        gridLayout.addWidget(self.section2GroupBox, 0, 2)

        sectionLayout = QHBoxLayout()
        sectionLayout.addLayout(gridLayout)

        self.connectionIdWidget = self.createMainContentNumWidget()
        connectionIdLayout = QHBoxLayout()
        layout.addLayout(connectionIdLayout)
        connectionIdLayout.addWidget(self.connectionIdWidget)
        connectionIdLayout.addStretch(1)

        layout.addLayout(sectionLayout)

        mainGroupBox = QGroupBox("主捆绑")
        mainLayout = QVBoxLayout()

        pointGroupBox = QGroupBox("捆绑点")
        pointLayout = QVBoxLayout()
        self.mainWidgetDict["mainPointTable"] = ParamsTable(rows=0, columns=4)
        self.mainWidgetDict["mainPointTable"].setHorizontalHeaderLabels(
            [
                "id",
                "轴向坐标",
                "径向坐标",
                "连接自由度",
            ]
        )

        self.mainWidgetDict["mainPointTable"].rowSetFloat([1, 2])
        self.mainWidgetDict["mainPointTable"].rowSetInt([0, 3])
        pointLayout.addWidget(self.mainWidgetDict["mainPointTable"])
        pointGroupBox.setLayout(pointLayout)

        boltGroupBox = QGroupBox("捆绑螺栓")
        boltLayout = QVBoxLayout()
        self.mainWidgetDict["mainBoltTable"] = ParamsTable(rows=0, columns=4)
        self.mainWidgetDict["mainBoltTable"].setFixedHeight(singleHeight)
        self.mainWidgetDict["mainBoltTable"].setHorizontalHeaderLabels(
            [
                "id",
                "外径",
                "内径",
                "材料",
            ]
        )
        self.mainWidgetDict["mainBoltTable"].rowSetInt([0])
        self.mainWidgetDict["mainBoltTable"].rowSetFloat([1, 2])
        self.mainWidgetDict["mainBoltTable"].rowSetSelect(
            [3], options={"3": self.materialOptions}
        )
        boltLayout.addWidget(self.mainWidgetDict["mainBoltTable"])
        boltGroupBox.setLayout(boltLayout)
        mainLayout.addWidget(pointGroupBox)
        mainLayout.addWidget(boltGroupBox)

        mainGroupBox.setLayout(mainLayout)

        layout.addWidget(mainGroupBox)

        self.mainPage.setLayout(layout)

    def createRodPage(self):
        layoutWrap = QHBoxLayout()
        layout = QVBoxLayout()
        layoutWrap.addStretch(1)
        layoutWrap.addLayout(layout)
        layoutWrap.addStretch(1)

        gridLayout = QGridLayout()
        self.section1GroupBox = QGroupBox(
            self.connects.get("connectsTitles")[0].get("title")
        )
        section1Layout = QVBoxLayout()
        self.section1GroupBox.setLayout(section1Layout)
        self.rodWidgetDict["rodSection1"] = SelectBox(
            options=[
                {"title": "点", "value": "点"},
                {"title": "蒙皮桁条", "value": "蒙皮桁条"},
            ],
            onChanged=lambda *args, **kwargs: self.rodSection1Changed(
                self, *args, **kwargs
            ),
        )

        self.rodWidgetDict["rodSection1Value"] = SelectSearchBox(options=[])
        self.rodWidgetDict["rodSection1"].setMinimumWidth(100)
        self.rodWidgetDict["rodSection1Value"].setMinimumWidth(100)
        self.rodWidgetDict["rodSection1"].setMaximumWidth(150)
        self.rodWidgetDict["rodSection1Value"].setMaximumWidth(150)
        section1Layout.addWidget(self.rodWidgetDict["rodSection1"])
        section1Layout.addWidget(self.rodWidgetDict["rodSection1Value"])

        coordinates1GroupBox = QGroupBox("支座点坐标")
        coordinates1Layout = QVBoxLayout()
        self.rodWidgetDict["rodCoordinates1Table"] = ParamsTable(rows=0, columns=4)
        # self.rodWidgetDict['rodCoordinates1Table'].setFixedHeight(singleHeight)
        self.rodWidgetDict["rodCoordinates1Table"].setHorizontalHeaderLabels(
            [
                "id",
                "轴向坐标",
                "径向坐标",
                "角度",
            ]
        )
        self.rodWidgetDict["rodCoordinates1Table"].rowSetInt([0])
        self.rodWidgetDict["rodCoordinates1Table"].rowSetFloat([1, 2, 3])
        coordinates1Layout.addWidget(self.rodWidgetDict["rodCoordinates1Table"])
        coordinates1GroupBox.setLayout(coordinates1Layout)
        section1Layout.addWidget(coordinates1GroupBox)

        self.rodscope1GroupBox = QGroupBox("支座范围")
        self.rodscope1GroupBox.setVisible(False)
        scope1Layout = QVBoxLayout()
        self.rodWidgetDict["rodScope1Table"] = ParamsTable(rows=0, columns=1)
        # self.rodWidgetDict['rodScope1Table'].setFixedHeight(singleHeight)
        self.rodWidgetDict["rodScope1Table"].setHorizontalHeaderLabels(
            [
                "角度",
            ]
        )
        self.rodWidgetDict["rodScope1Table"].rowSetFloat([0])
        self.rodWidgetDict["rodScope1Table"].useFlag = False
        scope1Layout.addWidget(self.rodWidgetDict["rodScope1Table"])
        self.rodscope1GroupBox.setLayout(scope1Layout)
        section1Layout.addWidget(self.rodscope1GroupBox)

        self.section2GroupBox = QGroupBox(
            self.connects.get("connectsTitles")[1].get("title")
        )
        section2Layout = QVBoxLayout()
        self.section2GroupBox.setLayout(section2Layout)
        self.rodWidgetDict["rodSection2"] = SelectBox(
            options=[],
            onChanged=lambda *args, **kwargs: self.rodSection2Changed(
                self, *args, **kwargs
            ),
        )
        self.rodWidgetDict["rodSection2Value"] = SelectSearchBox(options=[])
        self.rodWidgetDict["rodSection2"].setMinimumWidth(100)
        self.rodWidgetDict["rodSection2Value"].setMinimumWidth(100)
        self.rodWidgetDict["rodSection2"].setMaximumWidth(150)
        self.rodWidgetDict["rodSection2Value"].setMaximumWidth(150)
        section2Layout.addWidget(self.rodWidgetDict["rodSection2"])
        section2Layout.addWidget(self.rodWidgetDict["rodSection2Value"])

        coordinates2GroupBox = QGroupBox("支座点坐标")
        coordinates2Layout = QVBoxLayout()
        self.rodWidgetDict["rodCoordinates2Table"] = ParamsTable(rows=0, columns=5)
        self.rodWidgetDict["rodCoordinates2Table"].setHorizontalHeaderLabels(
            [
                "id",
                "轴向坐标",
                "径向坐标",
                "角度1",
                "角度2",
            ]
        )
        self.rodWidgetDict["rodCoordinates2Table"].rowSetInt([0])
        self.rodWidgetDict["rodCoordinates2Table"].rowSetFloat([1, 2, 3, 4])
        coordinates2Layout.addWidget(self.rodWidgetDict["rodCoordinates2Table"])
        coordinates2GroupBox.setLayout(coordinates2Layout)
        section2Layout.addWidget(coordinates2GroupBox)

        self.rodscope2GroupBox = QGroupBox("支座范围")
        self.rodscope2GroupBox.setVisible(False)
        scope2Layout = QVBoxLayout()
        self.rodWidgetDict["rodScope2Table"] = ParamsTable(rows=0, columns=1)
        self.rodWidgetDict["rodScope2Table"].setHorizontalHeaderLabels(
            [
                "角度",
            ]
        )
        self.rodWidgetDict["rodScope2Table"].rowSetFloat([0])
        self.rodWidgetDict["rodScope2Table"].useFlag = False
        scope2Layout.addWidget(self.rodWidgetDict["rodScope2Table"])
        self.rodscope2GroupBox.setLayout(scope2Layout)
        section2Layout.addWidget(self.rodscope2GroupBox)

        icon = envs.qicons.qicon_add_by_rotate()
        addImg = QLabel()
        addImg.setAlignment(Qt.AlignCenter)
        pixmap = icon.pixmap(20, 20)
        addImg.setPixmap(pixmap)

        gridLayout.addWidget(self.section1GroupBox, 0, 0)
        gridLayout.addWidget(addImg, 0, 1)
        gridLayout.addWidget(self.section2GroupBox, 0, 2)

        sectionLayout = QHBoxLayout()
        sectionLayout.addStretch(1)
        sectionLayout.addLayout(gridLayout)
        sectionLayout.addStretch(1)

        self.connectionIdWidget = self.createRodContentNumWidget()
        connectionIdLayout = QHBoxLayout()
        layout.addLayout(connectionIdLayout)
        connectionIdLayout.addWidget(self.connectionIdWidget)
        connectionIdLayout.addStretch(1)

        layout.addLayout(sectionLayout)

        rodsGroupBox = QGroupBox("捆绑连杆")
        rodsLayout = QVBoxLayout()
        self.rodWidgetDict["rodsTable"] = ParamsTable(rows=0, columns=4)
        self.rodWidgetDict["rodsTable"].setHorizontalHeaderLabels(
            [
                "id",
                "外径",
                "内径",
                "材料",
            ]
        )
        self.rodWidgetDict["rodsTable"].rowSetInt([0])
        # self.rodWidgetDict['rodsTable'].setFixedHeight(singleHeight)
        self.rodWidgetDict["rodsTable"].rowSetFloat([1, 2])
        self.rodWidgetDict["rodsTable"].rowSetSelect(
            [3], options={"3": self.materialOptions}
        )
        rodsLayout.addWidget(self.rodWidgetDict["rodsTable"])
        rodsGroupBox.setLayout(rodsLayout)

        layout.addWidget(rodsGroupBox)
        self.rodPage.setLayout(layoutWrap)

    def libraryChange(self, library):
        if self.isVisible():
            self.materialData = library

    def parseContects(self, contects):
        optionsDict1 = {}
        optionsDict2 = {}

        stages = contects.get("stages") or []
        sections0 = stages[0].get("sections") or {}
        for i, item in enumerate(sections0):
            data = item.get("data") or {}

            if data.get("type") == "shell_bar":
                ids = self.getIds(type=data.get("type"), data=data)
                optionsDict1["shell_bar"] = (
                    (optionsDict1.get("shell_bar") or []) + ids + [f"section{i+1}"]
                )
            elif data.get("type") == "point_mass":
                ids = self.getIds(type=data.get("type"), data=data)
                optionsDict1["point_mass"] = (
                    (optionsDict1.get("point_mass") or []) + ids + [f"section{i+1}"]
                )
            elif data.get("type") == "bar_conm":
                ids = self.getIds(type=data.get("type"), data=data)
                optionsDict1["bar_conm"] = (
                    (optionsDict1.get("bar_conm") or []) + ids + [f"section{i+1}"]
                )
            elif data.get("type") == "bar_3d":
                ids = self.getIds(type=data.get("type"), data=data)
                optionsDict1["bar_3d"] = (
                    (optionsDict1.get("bar_3d") or []) + ids + [f"section{i+1}"]
                )

        sections1 = stages[1].get("sections") or {}
        for i, item in enumerate(sections1):
            data = item.get("data") or {}

            if data.get("type") == "shell_bar":
                ids = self.getIds(type=data.get("type"), data=data)
                optionsDict2["shell_bar"] = (
                    (optionsDict2.get("shell_bar") or []) + ids + [f"section{i+1}"]
                )
            elif data.get("type") == "point_mass":
                ids = self.getIds(type=data.get("type"), data=data)
                optionsDict2["point_mass"] = (
                    (optionsDict2.get("point_mass") or []) + ids + [f"section{i+1}"]
                )
            elif data.get("type") == "bar_conm":
                ids = self.getIds(type=data.get("type"), data=data)
                optionsDict2["bar_conm"] = (
                    (optionsDict2.get("bar_conm") or []) + ids + [f"section{i+1}"]
                )
            elif data.get("type") == "bar_3d":
                ids = self.getIds(type=data.get("type"), data=data)
                optionsDict2["bar_3d"] = (
                    (optionsDict2.get("bar_3d") or []) + ids + [f"section{i+1}"]
                )

        converted_dict1 = Utils.convertedSortAndFormat(optionsDict1)
        converted_dict2 = Utils.convertedSortAndFormat(optionsDict2)

        dataDict = {}

        dataDict["options0"] = converted_dict1
        dataDict["options1"] = converted_dict2

        return dataDict

    def getIds(self, type, data={}):
        ids = []
        if data:
            if type == "shell_bar":
                ringFrameData = (data.get("grid_set") or [[]]) + (
                    data.get("grid_ring") or [[]]
                )
                for item in ringFrameData:
                    if len(item) > 0:
                        ids.append(item[0])
            elif type == "bar_3d":
                if data.get("grid"):
                    if len(data.get("grid")) > 0 and len(data["grid"][0]) > 0:
                        ids.append(data["grid"][0][0])
                    if len(data.get("grid")) > 1 and len(data["grid"][1]) > 0:
                        ids.append(data["grid"][1][0])
            elif type == "point_mass":
                ids.append(data.get("grid_id"))
            elif type == "bar_conm":
                main = data.get("main") or []
                for item in main:
                    if item and isinstance(item, list) and len(item) > 0:
                        ids.append(item[0])

        ids = [item for item in ids if item is not None]

        return ids

    # @classmethod
    # def show(cls, parent=None, params={}):
    #     data1 = Utils.read_json(Config.cachePath + "beamAndMassPoint.json")
    #     data2 = Utils.read_json(Config.cachePath + "skeletalStructure.json")
    #     data3 = Utils.read_json(Config.cachePath + "stringer.json")
    #     params = {
    #         "data": {},
    #         "info": {
    #             "connectType": "Stage",
    #             "connects": [
    #                 {
    #                     "title": "Stage3",
    #                     "data": {
    #                         "sections": [
    #                             {"type": "梁与质量点建模", "data": {"data":data1}},
    #                             # {"type": "杆系建模", "data": data2},
    #                             # {"type": "蒙皮桁条建模", "data": data3},
    #                         ]
    #                     },
    #                 },
    #                 {
    #                     "title": "Stage4",
    #                     "data": {
    #                         "sections": [
    #                             {"type": "梁与质量点建模", "data": {"data":data1}},
    #                             {"type": "蒙皮桁条建模", "data": {"data":data3}},
    #                         ]
    #                     },
    #                 },
    #             ],
    #         },
    #     }
    # params = {
    #     "data": {},
    #     "info": {
    #         "connectType": "Section",
    #         "connects": [
    #             {
    #                 "title": "Section4",
    #                 "type": "杆系建模",
    #                 "data": data2,
    #             },
    #             {
    #                 "title": "Section3",
    #                 "type": "梁与质量点建模",
    #                 "data": data1,
    #             },

    #         ],
    #     },
    # }
    # if cls._shown:
    #     cls._instance.activateWindow()
    #     cls._instance.raise_()
    # else:
    #     cls._shown = True
    #     cls._instance = cls(parent=parent, params=params)  # 创建新实例并传入parent
    #     cls._instance.setParent(parent)  # 设置父窗口
    #     QDialog.show(cls._instance)  # 直接调用QDialog的show方法
    #     return cls._instance

    def getMaterialOption(self):
        options = []
        self.materialData = (
            Utils.read_json(Config.cachePath + "materialLibrary.json") or {}
        )
        if self.materialData:
            for key, _ in self.materialData.items():
                options.append({"title": key, "value": key})
        return options

    def createFreeWidget(self):
        self.mainWidgetDict["mainFreeTable"] = ParamsTable(rows=0, columns=2)
        self.mainWidgetDict["mainFreeTable"].setHorizontalHeaderLabels(
            [
                "主节点",
                "从节点",
            ]
        )
        self.mainWidgetDict["mainFreeTable"].rowSetInt([0])
        return self.mainWidgetDict["mainFreeTable"]

    def on_okBtn_clicked(self):
        mainDict = {}
        rodDict = {}
        for key, widget in self.mainWidgetDict.items():
            if hasattr(widget, "useFlag") and getattr(widget, "useFlag") == False:
                continue
            if isinstance(widget, QTableWidget):
                temp = widget.getTableData()
                if key == "mainPointTable":
                    mainDict[mainConnectMap[key]] = temp
                else:
                    if temp and len(temp) >= 1:
                        mainDict[mainConnectMap[key]] = temp[0]

            else:
                if key == "mainSection1" or key == "mainSection2":
                    continue
                if (
                    key == "mainSection1Value"
                    and isinstance(widget.getValue(), str)
                    and "section" in widget.getValue()
                ):
                    mainDict["section1"] = widget.getValue()
                    continue
                if (
                    key == "mainSection2Value"
                    and isinstance(widget.getValue(), str)
                    and "section" in widget.getValue()
                ):
                    mainDict["section2"] = widget.getValue()
                    continue
                mainDict[mainConnectMap[key]] = widget.getValue()

        for key, widget in self.rodWidgetDict.items():
            if hasattr(widget, "useFlag") and getattr(widget, "useFlag") == False:
                continue
            if isinstance(widget, QTableWidget):
                temp = widget.getTableData()

                if (
                    temp
                    and len(temp) >= 1
                    and key != "rodScope1Table"
                    and key != "rodScope2Table"
                ):
                    rodDict[rodConnectMap[key]] = temp[0]
                elif temp:
                    flattened_list = [item for sublist in temp for item in sublist]

                    rodDict[rodConnectMap[key]] = flattened_list
            else:
                if key == "rodSection1" or key == "rodSection2":
                    continue
                if (
                    key == "rodSection1Value"
                    and isinstance(widget.getValue(), str)
                    and "section" in widget.getValue()
                ):
                    rodDict["section1"] = widget.getValue()
                    continue
                if (
                    key == "rodSection2Value"
                    and isinstance(widget.getValue(), str)
                    and "section" in widget.getValue()
                ):
                    rodDict["section2"] = widget.getValue()
                    continue
                rodDict[rodConnectMap[key]] = widget.getValue()

        mainDict["type"] = (
            str(typeBundleMap.get(self.mainWidgetDict["mainSection1"].getValue()))
            + "2"
            + str(typeBundleMap.get(self.mainWidgetDict["mainSection2"].getValue()))
        )
        mainDict["part1"] = self.connects.get("connectsTitles")[0].get("title")
        mainDict["part2"] = self.connects.get("connectsTitles")[1].get("title")

        rodDict["type"] = (
            str(typeBundleMap.get(self.rodWidgetDict["rodSection1"].getValue()))
            + "2"
            + str(typeBundleMap.get(self.rodWidgetDict["rodSection2"].getValue()))
        )

        rodDict["part1"] = self.connects.get("connectsTitles")[0].get("title")
        rodDict["part2"] = self.connects.get("connectsTitles")[1].get("title")

        mainDict = Utils.filter_dict_list(mainDict)
        mainDict = Utils.filterDictEmptyProperty(mainDict)
        rodDict = Utils.filter_dict_list(rodDict)
        rodDict = Utils.filterDictEmptyProperty(rodDict)

        dict = {"main": mainDict, "rod": rodDict}

        self.cacheFile = Config.cachePath + "bundleConnection.json"
        Utils.write_json(self.cacheFile, dict)
        self.close()
        self.bundleConnection_save_signal.emit(dict)

    def updateUI(self, data, widgetDict, flag):
        if data:
            for key, value in data.items():
                if flag == "main":
                    widget = mainConnectReverseMap.get(key)
                else:
                    widget = rodConnectReverseMap.get(key)
                if widget in widgetDict:
                    if isinstance(widgetDict[widget], QTableWidget):
                        temp = []
                        if widget == "mainPointTable":
                            continue
                        if widget == "rodScope1Table" or widget == "rodScope2Table":
                            if value:
                                temp = [[item] for item in value]
                        else:
                            temp = [value]
                        for rowData in temp:
                            widgetDict[widget].addRow(rowData=rowData)
                    elif isinstance(widgetDict[widget], QComboBox):
                        widgetDict[widget].setValue(str(value))
                    else:
                        if (
                            widget == "mainSection1"
                            or widget == "mainSection2"
                            or widget == "rodSection1"
                            or widget == "rodSection2"
                        ):
                            continue
                        widgetDict[widget].setValue(value)

            if flag == "main":
                type = data.get("type")
                if type and "2" in type:
                    parts = re.split(r"2", type)  # 使用数字作为分隔符分割字符串
                    widgetDict["mainSection1"].setValue(
                        typeBundleReverseMap.get(parts[0])
                    )
                    widgetDict["mainSection2"].setValue(
                        typeBundleReverseMap.get(parts[-1])
                    )

                if data.get("con_id1"):
                    widgetDict["mainSection1Value"].setValue(
                        Utils.toInt(data.get("con_id1"))
                    )
                elif data.get("section1"):
                    widgetDict["mainSection1Value"].setValue(data.get("section1"))

                if data.get("con_id2"):
                    widgetDict["mainSection2Value"].setValue(
                        Utils.toInt(data.get("con_id2"))
                    )
                elif data.get("section2"):
                    widgetDict["mainSection2Value"].setValue(data.get("section2"))

                # widgetDict["mainSection2Value"].setValue(Utils.toInt(data.get("con_id2")))
                for rowData in data.get("con_grid") or []:
                    widgetDict["mainPointTable"].addRow(rowData=rowData)
            else:
                type = data.get("type")
                if type and "2" in type:
                    parts = re.split(r"2", type)  # 使用数字作为分隔符分割字符串
                    widgetDict["rodSection1"].setValue(
                        typeBundleReverseMap.get(parts[0])
                    )
                    widgetDict["rodSection2"].setValue(
                        typeBundleReverseMap.get(parts[-1])
                    )

                if data.get("con_id1"):
                    widgetDict["rodSection1Value"].setValue(
                        Utils.toInt(data.get("con_id1"))
                    )
                elif data.get("section1"):
                    widgetDict["rodSection1Value"].setValue(data.get("section1"))

                if data.get("con_id2"):
                    widgetDict["rodSection2Value"].setValue(
                        Utils.toInt(data.get("con_id2"))
                    )
                elif data.get("section2"):
                    widgetDict["rodSection2Value"].setValue(data.get("section2"))

    def addTab(self):
        tabNames = [self.tabs.tabText(i) for i in range(self.tabs.count())]
        dlgAddConnection = DlgAddConnection.show(
            parent=self, params={"names": tabNames}
        )
        dlgAddConnection.ok_signal.connect(self.updateTabbar)

    def updateTabbar(self, data={}):
        if data:
            self.tabs.addTab(self.createMainContentNumWidget(), data.get("name"))
            self.tabs.setCurrentIndex(self.tabs.count() - 1)

    # main
    def createMainContentNumWidget(self):
        connectionIdWidget = QWidget()
        connectionIdWidget.setFixedWidth(240)
        connectionIdLayout = QGridLayout()
        label1 = QLabel("连接的自由度")
        self.mainWidgetDict["mainConnectionId"] = LineEditInt()
        self.mainWidgetDict["mainConnectionId"].setClearButtonEnabled(False)
        self.mainWidgetDict["mainConnectionId"].setValue(123456)
        connectionIdLayout.addWidget(label1, 0, 0)
        connectionIdLayout.addWidget(self.mainWidgetDict["mainConnectionId"], 0, 1)

        label2 = QLabel("id")
        self.mainWidgetDict["mainId"] = LineEditInt()
        self.mainWidgetDict["mainId"].setClearButtonEnabled(False)
        connectionIdLayout.addWidget(label2, 1, 0)
        connectionIdLayout.addWidget(self.mainWidgetDict["mainId"], 1, 1)
        connectionIdWidget.setLayout(connectionIdLayout)

        return connectionIdWidget

    def getMainStageOptionData(self, select, index):
        options = []
        ls = self.info.get(f"options{index}")
        if select == "点":
            options = ls.get("bar_conm") or []
        elif select == "蒙皮桁条":
            options = ls.get("shell_bar") or []
        return options

    def mainSection1Changed(self, *args):
        if args[1] == "点":
            if (
                self.connectType == "Stage"
                or self.connectType == "Booster"
                or self.connectType == "Fairing"
            ):

                self.setMainStageOptions(
                    options=(self.info.get("options1") or {}),
                    select=self.mainWidgetDict["mainSection2"],
                    previous="点",
                )
                options = self.getMainStageOptionData("点", 0)
                self.mainWidgetDict["mainSection1Value"].updateItem(options)
            self.mainWidgetDict["mainSection1Value"].setVisible(True)
            self.mainWidgetDict["mainSection2Value"].setVisible(True)
            self.mainWidgetDict["mainSection1Value"].useFlag = True
            self.mainWidgetDict["mainSection2Value"].useFlag = True
        if args[1] == "蒙皮桁条":
            if (
                self.connectType == "Stage"
                or self.connectType == "Booster"
                or self.connectType == "Fairing"
            ):
                self.setMainStageOptions(
                    options=(self.info.get("options1") or {}),
                    select=self.mainWidgetDict["mainSection2"],
                    previous="蒙皮桁条",
                )
                options = self.getMainStageOptionData("蒙皮桁条", 0)
                self.mainWidgetDict["mainSection1Value"].updateItem(options)
            self.mainWidgetDict["mainSection1Value"].setVisible(True)
            self.mainWidgetDict["mainSection2Value"].setVisible(True)
            self.mainWidgetDict["mainSection1Value"].useFlag = True
            self.mainWidgetDict["mainSection2Value"].useFlag = True

        self.showMainTable()

    def mainSection2Changed(self, *args):
        if (
            self.connectType == "Stage"
            or self.connectType == "Booster"
            or self.connectType == "Fairing"
        ):
            if args[1] == "点":
                options = self.getMainStageOptionData("点", 1)
                self.mainWidgetDict["mainSection2Value"].updateItem(options)
            if args[1] == "蒙皮桁条":
                options = self.getMainStageOptionData("蒙皮桁条", 1)
                self.mainWidgetDict["mainSection2Value"].updateItem(options)
        self.showMainTable()

    def showMainTable(self):
        if self.mainWidgetDict["mainSection1"].getValue() == "点":
            self.mainscope1GroupBox.setVisible(False)
            self.mainWidgetDict["mainScope1Table"].useFlag = False
        elif self.mainWidgetDict["mainSection1"].getValue() == "蒙皮桁条":
            self.mainscope1GroupBox.setVisible(True)
            self.mainWidgetDict["mainScope1Table"].useFlag = True
        else:
            self.mainscope1GroupBox.setVisible(False)
            self.mainWidgetDict["mainScope1Table"].useFlag = False

        if self.mainWidgetDict["mainSection2"].getValue() == "点":
            self.mainscope2GroupBox.setVisible(False)
            self.mainWidgetDict["mainScope2Table"].useFlag = False
        elif self.mainWidgetDict["mainSection2"].getValue() == "蒙皮桁条":
            self.mainscope2GroupBox.setVisible(True)
            self.mainWidgetDict["mainScope2Table"].useFlag = True
        else:
            self.mainscope2GroupBox.setVisible(False)
            self.mainWidgetDict["mainScope2Table"].useFlag = False

    def setMainStageOptions(self, options, select, previous=""):
        opt = []
        if "bar_conm" in options:
            # if previous == "点" or previous == "蒙皮桁条" or previous == "":
            if {"title": "点", "value": "点"} not in opt:
                opt.append({"title": "点", "value": "点"})
        if "shell_bar" in options:
            # if previous == "点" or previous == "蒙皮桁条" or previous == "":
            if {"title": "蒙皮桁条", "value": "蒙皮桁条"} not in opt:
                opt.append({"title": "蒙皮桁条", "value": "蒙皮桁条"})
        select.updateItem(opt)

    # rod
    def createRodContentNumWidget(self):
        connectionIdWidget = QWidget()
        connectionIdWidget.setFixedWidth(240)
        connectionIdLayout = QGridLayout()
        label1 = QLabel("连接的自由度")
        self.rodWidgetDict["rodConnectionId"] = LineEditInt()
        self.rodWidgetDict["rodConnectionId"].setClearButtonEnabled(False)
        self.rodWidgetDict["rodConnectionId"].setValue(123456)
        connectionIdLayout.addWidget(label1, 0, 0)
        connectionIdLayout.addWidget(self.rodWidgetDict["rodConnectionId"], 0, 1)

        label2 = QLabel("id")
        self.rodWidgetDict["rodId"] = LineEditInt()
        self.rodWidgetDict["rodId"].setClearButtonEnabled(False)
        connectionIdLayout.addWidget(label2, 1, 0)
        connectionIdLayout.addWidget(self.rodWidgetDict["rodId"], 1, 1)
        connectionIdWidget.setLayout(connectionIdLayout)
        return connectionIdWidget

    def getRodStageOptionData(self, select, index):
        options = []
        ls = self.info.get(f"options{index}")
        if select == "点":
            options = ls.get("bar_conm") or []
        elif select == "蒙皮桁条":
            options = ls.get("shell_bar") or []
        return options

    def rodSection1Changed(self, *args):
        if args[1] == "点":

            if (
                self.connectType == "Stage"
                or self.connectType == "Booster"
                or self.connectType == "Fairing"
            ):
                self.setRodStageOptions(
                    options=(self.info.get("options1") or {}),
                    select=self.rodWidgetDict["rodSection2"],
                    previous="点",
                )
                options = self.getRodStageOptionData("点", 0)
                self.rodWidgetDict["rodSection1Value"].updateItem(options)
            self.rodWidgetDict["rodSection1Value"].setVisible(True)
            self.rodWidgetDict["rodSection2Value"].setVisible(True)
            self.rodWidgetDict["rodSection1Value"].useFlag = True
            self.rodWidgetDict["rodSection2Value"].useFlag = True
        if args[1] == "蒙皮桁条":
            if (
                self.connectType == "Stage"
                or self.connectType == "Booster"
                or self.connectType == "Fairing"
            ):
                self.setRodStageOptions(
                    options=(self.info.get("options1") or {}),
                    select=self.rodWidgetDict["rodSection2"],
                    previous="蒙皮桁条",
                )
                options = self.getRodStageOptionData("蒙皮桁条", 0)
                self.rodWidgetDict["rodSection1Value"].updateItem(options)
            self.rodWidgetDict["rodSection1Value"].setVisible(True)
            self.rodWidgetDict["rodSection2Value"].setVisible(True)
            self.rodWidgetDict["rodSection1Value"].useFlag = True
            self.rodWidgetDict["rodSection2Value"].useFlag = True
        self.showRodTable()

    def rodSection2Changed(self, *args):
        if (
            self.connectType == "Stage"
            or self.connectType == "Booster"
            or self.connectType == "Fairing"
        ):
            if args[1] == "点":
                options = self.getRodStageOptionData("点", 1)
                self.rodWidgetDict["rodSection2Value"].updateItem(options)
            if args[1] == "蒙皮桁条":
                options = self.getRodStageOptionData("蒙皮桁条", 1)
                self.rodWidgetDict["rodSection2Value"].updateItem(options)
        self.showRodTable()

    def showRodTable(self):
        if self.rodWidgetDict["rodSection1"].getValue() == "点":
            self.rodscope1GroupBox.setVisible(False)
            self.rodWidgetDict["rodScope1Table"].useFlag = False
        elif self.rodWidgetDict["rodSection1"].getValue() == "蒙皮桁条":
            self.rodscope1GroupBox.setVisible(True)
            self.rodWidgetDict["rodScope1Table"].useFlag = True
        else:
            self.rodscope1GroupBox.setVisible(False)
            self.rodWidgetDict["rodScope1Table"].useFlag = False

        if self.rodWidgetDict["rodSection2"].getValue() == "点":
            self.rodscope2GroupBox.setVisible(False)
            self.rodWidgetDict["rodScope2Table"].useFlag = False
        elif self.rodWidgetDict["rodSection2"].getValue() == "蒙皮桁条":
            self.rodscope2GroupBox.setVisible(True)
            self.rodWidgetDict["rodScope2Table"].useFlag = True
        else:
            self.rodscope2GroupBox.setVisible(False)
            self.rodWidgetDict["rodScope2Table"].useFlag = False

    def setRodStageOptions(self, options, select, previous=""):

        opt = []

        if "bar_conm" in options:
            # if previous == "点" or previous == "":
            if {"title": "点", "value": "点"} not in opt:
                opt.append({"title": "点", "value": "点"})
        if "shell_bar" in options:
            # if previous == "点" or previous == "蒙皮桁条" or previous == "":
            if {"title": "蒙皮桁条", "value": "蒙皮桁条"} not in opt:
                opt.append({"title": "蒙皮桁条", "value": "蒙皮桁条"})
        select.updateItem(opt)


# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     window = BundleConnectionDialog()
#     window.show()
#     sys.exit(app.exec_())
